import 'package:chewie/chewie.dart' hide MaterialControls;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_billi/util/color.dart';
import 'package:flutter_billi/util/view_util.dart';
import 'package:flutter_billi/widget/hi_video_player.dart';
import 'package:orientation/orientation.dart';
import 'package:video_player/video_player.dart';

class VideoView extends StatefulWidget {
  final String url;
  final String cover;
  final bool autoPlay;
  final bool looping;
  final double aspectRation;
  final Widget overlayUI;

  const VideoView(
    this.url, {
    Key key,
    this.cover,
    this.autoPlay = false,
    this.looping = false,
    this.aspectRation = 16 / 9,
    this.overlayUI,
  }) : super(key: key);

  @override
  _VideoViewState createState() => _VideoViewState();
}

class _VideoViewState extends State<VideoView> {
  VideoPlayerController _videoPlayerController;
  ChewieController _chewieController;

// 封面
  get _placeholder => FractionallySizedBox(
        widthFactor: 1,
        child: cachedImage(widget.cover),
      );
  // 进度条颜色
  get _progressColors => ChewieProgressColors(
        playedColor: primay,
        handleColor: primay,
        backgroundColor: Colors.grey,
        bufferedColor: primay[50],
      );
  @override
  void initState() {
    super.initState();
    // 初始化播放器设置
    _videoPlayerController = VideoPlayerController.network(widget.url);
    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController,
      aspectRatio: widget.aspectRation,
      autoPlay: widget.autoPlay,
      looping: widget.looping,
      allowMuting: false,
      allowPlaybackSpeedChanging: false, // 控制播放速度
      customControls: MaterialControls(
        showLoadingOnInitialize: false,
        showBigPlayIcon: false,
        bottomGradient: blackLinearGradient(),
        overlayUI: widget.overlayUI,
      ),
      placeholder: _placeholder,
      materialProgressColors: _progressColors,
    );
    _chewieController.addListener(_fullScreenListener);
  }

  @override
  void dispose() {
    _chewieController.removeListener(_fullScreenListener);
    _videoPlayerController.dispose();
    _chewieController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double screeWidth = MediaQuery.of(context).size.width;
    double screenHeight = screeWidth / widget.aspectRation;

    return Container(
      width: screeWidth,
      height: screenHeight,
      color: Colors.grey,
      child: Chewie(
        controller: _chewieController,
      ),
    );
  }

  void _fullScreenListener() {
    Size size = MediaQuery.of(context).size;
    if (size.width > size.height) {
      // OrientationPlugin.
      OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
    }
  }
}
